package com.chenyi.web.controller.system;

import com.chenyi.common.annotation.Log;
import com.chenyi.common.config.ChenYiConfig;
import com.chenyi.common.constant.Constants;
import com.chenyi.common.core.controller.BaseController;
import com.chenyi.common.core.domain.entity.SysAdmin;
import com.chenyi.common.core.domain.model.LoginAdmin;
import com.chenyi.common.enums.BusinessType;
import com.chenyi.common.exception.BadRequestException;
import com.chenyi.common.exception.MessageException;
import com.chenyi.common.utils.AdminUtils;
import com.chenyi.common.utils.ServletUtils;
import com.chenyi.file.config.FileConfig;
import com.chenyi.framework.web.service.AdminTokenService;
import com.chenyi.file.utils.FileUploadUtils;
import com.chenyi.system.service.ISysAdminService;
import com.google.common.collect.Maps;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * 个人信息 业务处理
 * 
 * @author wangkh
 */
@RestController
@RequestMapping("/admin/admin/profile")
public class AdminProfileController extends BaseController
{
    @Autowired
    private ISysAdminService userService;

    @Autowired
    private AdminTokenService tokenService;
    /**
     * 个人信息
     */
    @GetMapping
    public ResponseEntity<Object> profile()
    {
        LoginAdmin loginUser = tokenService.getLoginAdmin(ServletUtils.getRequest());
        SysAdmin user = loginUser.getAdmin();
        Map<String,Object> data = Maps.newHashMap();
        data.put("data",user);
        data.put("roleGroup", userService.selectAdminRoleGroup(loginUser.getUsername()));
        data.put("postGroup", userService.selectAdminPostGroup(loginUser.getUsername()));
        return ResponseEntity.ok(data);
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResponseEntity<Object> updateProfile(@RequestBody SysAdmin user)
    {
        if (userService.updateAdminProfile(user) > 0)
        {
            LoginAdmin loginUser = tokenService.getLoginAdmin(ServletUtils.getRequest());
            // 更新缓存用户信息
            loginUser.getAdmin().setNickName(user.getNickName());
            loginUser.getAdmin().setPhone(user.getPhone());
            loginUser.getAdmin().setEmail(user.getEmail());
            loginUser.getAdmin().setSex(user.getSex());
            tokenService.setLoginAdmin(loginUser);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        throw new BadRequestException("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public ResponseEntity<Object> updatePwd(String oldPassword, String newPassword)
    {
        LoginAdmin loginUser = tokenService.getLoginAdmin(ServletUtils.getRequest());
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!AdminUtils.matchesPassword(oldPassword, password))
        {
            throw new MessageException("修改密码失败，旧密码错误");
        }
        if (AdminUtils.matchesPassword(newPassword, password))
        {
            throw new MessageException("新密码不能与旧密码相同");
        }
        if (userService.resetAdminPwd(userName, AdminUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            loginUser.getAdmin().setPassword(AdminUtils.encryptPassword(newPassword));
            tokenService.setLoginAdmin(loginUser);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        throw new BadRequestException("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public ResponseEntity<Object> avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            LoginAdmin loginUser = tokenService.getLoginAdmin(ServletUtils.getRequest());
            String avatar = FileUploadUtils.upload(ChenYiConfig.getAvatarPath(), file);

            if (FileConfig.getUploadCompress()){
                String uploadUrl = ChenYiConfig.getProfile() + avatar.substring(Constants.RESOURCE_PREFIX.length());
                Thumbnails.of(uploadUrl)
                        .scale(1f)
                        .outputQuality(0.1f)
                        .toFile(uploadUrl);
            }

            if (userService.updateAdminAvatar(loginUser.getUsername(), avatar))
            {
                Map<String,Object> data = Maps.newHashMap();
                data.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getAdmin().setAvatar(avatar);
                tokenService.setLoginAdmin(loginUser);
                return ResponseEntity.ok(data);
            }
        }
        throw new BadRequestException("上传图片异常，请联系管理员");
    }
}
